$('#reset').click(function(){
    $('input').val('');
})
var dataSource = new Array();
//table的数据源
var table;   //table对象
dataSource = [];
var company_namess=""

jQuery.Huitab = function (tabBar, tabCon, class_name, tabEvent, i) {
    var $tab_menu = $(tabBar);
    // 初始化操作
    $tab_menu.removeClass(class_name);
    $(tabBar).eq(i).addClass(class_name);
    $(tabCon).hide();
    $(tabCon).eq(i).show();
    $tab_menu.bind(tabEvent, function () {
        $tab_menu.removeClass(class_name);
        $(this).addClass(class_name);
        var index = $tab_menu.index(this);
        $(tabCon).hide();
        $(tabCon).eq(index).show();
    });
}

$(function () {
    $.Huitab("#tab_goods .tabBar span", "#tab_goods .tabCon", "current", "click", "0")
});
// #tab_demo 父级id
// #tab_demo .tabBar span 控制条
// #tab_demo .tabCon 内容区
// click 事件 点击切换，可以换成mousemove 移动鼠标切换
// 1	默认第2个tab为当前状态（从0开始）

$(function () {
    $('.skin-minimal input').iCheck({
        checkboxClass: 'icheckbox-blue',
        radioClass: 'iradio-blue',
        increaseArea: '20%'
    })
});

var memberid = sessionStorage.getItem("member_id");
var arr1 = new Array(); //1级分类ID
var arr2 = new Array(); //2级分类ID
var arr3 = new Array(); //3级分类ID
var applcationRange; //适用范围 0:全部分类 1:指定分类 2:指定场景
var arr4 = new Array();//根据二级查询的一级分类ID 数组
var arr5 = new Array();//根据三级查询的二级分类ID 数组
init()
function init() {
    $.ajax({
        /*root.member.viewMember*/
        url: root.member.viewMember,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "memberId":memberid
        }),
        success: function (data) {
            console.log(data);
            console.log(data.member);
            //状态
            /*if (data.member.state == 10) {
                $('#state').html('待处理');
                $("#detail_statue").show();
            } else if (data.member.state == 20) {
                $('#state').html('处理中');
                $("#detail_statue").show();
            } else if (data.member.state == 30) {
                $('#state').html('已处理');
                $("#detail_statue").hide();
            }*/

            if(data.member.groundName!=""&& data.member.groundName!=null){
                $("#companyn").css({
                    display: "block"
                });
            }

            //描述
            $('#login_account').html(data.member.login_account);
            $('#mobile_phone').html(data.member.mobile_phone);
            $('#registerPlatform').html(data.member.register_platform);
            if(data.member.register_platform == 10){
                $('#registerPlatform').html('PC端');
            }else if (data.member.register_platform == 20) {
                $('#registerPlatform').html('Andriod端');

            }else if (data.member.register_platform == 30) {
                $('#registerPlatform').html('IOS端');

            }else if (data.member.register_platform == 40) {
                $('#registerPlatform').html('H5端');

            }else if (data.member.register_platform == 50) {
                $('#registerPlatform').html('云采后台');

            }else if (data.member.register_platform == 60) {
                $('#registerPlatform').html('小程序端');

            }
            $('#register_time').html(data.member.register_time_value);
            if(data.member.price_type==10){
                $('#price_type').html("售价");
            }else  if(data.member.price_type==20){
                $('#price_type').html("现金价");
            }
            // $('#price_type').html("售价");
            $('#email').html(data.member.email);
            if (data.member.groundName!=''&&data.member.groundName!=null) {
                if(data.member.status==10){
                    $('#groundName').html(data.member.groundName);
                }else {
                    $('#groundName').html(data.member.groundName+'(关闭)');
                }

            }
            if(data.member.customer_leader!=""){
                $('#customerleader').html(data.member.customer_leader);
            }
            if(data.member.company_name!=""){
                $('#companyname').html(data.member.company_name);
            }else {
                $('#companyname').html('');
            }
            $('#register_ip').html(data.member.register_ip);
            $('#register_addr').html(data.member.register_addr);
            if(data.generalInvoiceInfo!=null&&data.generalInvoiceInfo!=""){
                $('#company_name').html(data.generalInvoiceInfo.company_name);
                $('#taxpayer_code').html(data.generalInvoiceInfo.taxpayer_code);
                $('#General').removeAttr("style");
                $('#General').attr("onclick","generalvote()");
            }else {
                $("#General").attr("style","opacity: 0.2");
                $('#General').removeAttr('onclick');
            }

            $('#customer_name').html(data.member.customer_name);
            $('#customer_code').html(data.member.customer_code);
            $("#create_user").html(data.member.create_user);
        },
        error: function () {
            $.Huimodalalert('失败！');
        }
    });
}

//操作日志
adminzuo();
function adminzuo() {
$.ajax({
    /*root.member.optRecordList*/
    url: root.member.optRecordList,
    cache: false,  //禁用缓存
    type: "POST",
    dataType:'json',
    contentType: "application/json",
    data: JSON.stringify({
        memberId:memberid,
        "pageNum":1,

        "pageSize":20,

        "logType":"10"
    }),
    success: function (data) {
        console.log(data);
        console.log(data.list);
            if(data.list!=null){
                couponlist(data.list, 0);
            }else {
                couponlist(0, 0);
            }


        $('.M-box3').pagination({
            pageCount: data.totalPage,
            jump: true,
            coping: true,
            prevContent: '上页',
            nextContent: '下页',
            callback: function (api) {
                console.log(api)
                $.ajax({
                    /*root.member.optRecordList*/
                    url: root.member.optRecordList,
                    cache: false,  //禁用缓存
                    type: "POST",
                    dataType:'json',
                    contentType: "application/json",
                    data: JSON.stringify({
                        memberId:memberid,
                        "pageNum":api.getCurrent(),

                        "pageSize":20,

                        "logType":"10"
                    }),
                    success: function (result) {
                        console.log(result)
                        couponlist(result.list,0);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(XMLHttpRequest);
                    }
                });
            }
        });
        /* var handStr = '';

         if(data.list && data.list.length>0){
             $.each(data.list,function(k,v){
                 console.log(k);
                 console.log(v);
                 handStr+='<tr class="biaoge1">' +
                     '<td class="biaoge1-1"><span id="id">'+v.id+'</span></td>' +
                     '<td class="biaoge1-2"><span id="operate_username">'+v.operate_username+'</span></td>' +
                     '<td class="biaoge1-3"><span id="update_before">'+v.update_before+'</span></td>' +
                     '<td class="biaoge1-4"><span id="update_after">'+v.update_after+'</span></td>' +
                     '<td class="biaoge1-5"><span id="created_at_value">'+v.created_at_value+'</span></td>' +
                     '<td class="biaoge1-6"><span id="operate_type">'+v.operate_type+'</span></td>' +
                     '</tr>';

             });

             $("#tableId").find(".biaogeempty").remove();
             $("#tableId").find("tbody").append($(handStr));
             console.log(data.list)

         }*/

    },
    error: function () {
        $.Huimodalalert('失败！');
    }
});
}
function couponlist(data, index){
    // var j = 0;
    sessionStorage.setItem("authorizedUsers", JSON.stringify(data));
    dataSource.splice(0,dataSource.length);//清空数组
    if(data !=null && data != ''){
        var datashu =data[0].rowNo;
    }

    $.each(data, function (i, field) {
        var datashus = datashu++
        var rowData = new Array();
        rowData.push(field.id);
        rowData.push(field.opt_type);
        rowData.push(field.update_before);
        rowData.push(field.update_after);
        rowData.push(field.operate_username);
        rowData.push(field.created_at_value);
        rowData.push(datashus);
        rowData.push(field.belong_module);
        dataSource.push(rowData);

    });

    initDataTable(dataSource);

    function initDataTable(dataSource) {

        var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
        dttable.fnClearTable(); //清空一下table
        dttable.fnDestroy(); //还原初始化了的datatable
        $("#datatable").DataTable({
            // "order": false,
            "autoWidth": false,
            "ordering": false,
            "searching": false,
            "paging": false,
            "retrieve": true,
            "destroy": true,
            "bAutoWidth": true,
            "bLengthChange": true,
            "aLengthMenu": false,
            "oLanguage": {
                "sLengthMenu": "每页显示 _MENU_ 条记录",
                "sZeroRecords": "抱歉， 没有找到",
                "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
                "sInfoEmpty": "没有数据",
                "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
                "oPaginate": {
                    "sFirst": "首页",
                    "sPrevious": "前一页",
                    "sNext": "后一页",
                    "sLast": "尾页"
                },
                "sZeroRecords": "没有检索到数据",
            },
            data: dataSource,
            columnDefs: [
                {
                    "visible": true,
                    "targets": 0
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[6]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 0
                },

                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        if(row[1]==10){
                            val='修改手机号'
                        }
                        else if(row[1]==20){
                            val='修改业务联系人'
                        }
                        else if(row[1]==30){
                            val='修改业务联系人手机号'
                        }
                        else if(row[1]==40){
                            val='修改邮箱'
                        }
                        else if(row[1]==50 ){
                            val='状态'
                        }
                        else if(row[1]==60){
                            val='会员归属'
                        }
                        else if(row[1]==61){
                            val='公司所在地'
                        }
                        else if(row[1]==62){
                            val='详细地址'
                        }
                        else if(row[1]==63){
                            val='所属类型'
                        }
                        else if(row[1]==65){
                            val='营业执照'
                        }
                        else if(row[1]==66){
                            val='授权书'
                        }
                        else if(row[1]==67){
                            val='修改ip地理位置'
                        }
                        else if(row[1]==68){
                            val='会员负责人'
                        }
                        else if(row[1]==69){
                            val='单位名称'
                        }
                        else if(row[1]==70){
                            val='纳税人识别号'
                        }
                        else if(row[1]==75){
                            val='价格类型'
                        }

                        return val;
                    },
                    "targets":1
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[2];
                        if (row[1] == 50 && row[2] == 10) {
                            val='正常'
                        } else if (row[1] == 50 && row[2] == 20) {
                            val='关闭'
                        }else if (row[1] == 75 && row[2] == 10) {
                            val='售价'
                        }else if (row[1] == 75 && row[2] == 20) {
                            val='现金价'
                        }
                        return val;
                    },
                    "targets":2
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[3];
                        if (row[1] == 50 && row[3] == 10) {
                            val='正常'
                        } else if (row[1] == 50 && row[3] == 20) {
                            val='关闭'
                        }else if (row[1] == 75 && row[3] == 10) {
                            val='售价'
                        }else if (row[1] == 75 && row[3] == 20) {
                            val='现金价'
                        }
                        return val;
                    },
                    "targets":3
                },
                {
                    "render": function (data, type, row, meta) {
                        var val = row[4]
                        if (val == undefined) {
                            val = ''
                        }
                        return val;
                    },
                    "targets": 4
                },



                {
                    "render": function (data, type, row, meta) {
                        var val = '';
                        var date = row[5];
                        var split = date.split(" ");
                        val = split[0] + '<br/>' + split[1];
                        return val;
                    },
                    "targets":5
                },


            ]
        });

    };
}

/*$('#putout').attr('href',root.couponInter.coupon_exportProductExcel+id);*/

//编辑会员信息

function commom_edit() {
    $("#dizhi").modal("show");
    $(".addressTitle").html("客户基本信息更改");
    $("#companyNames").attr("disabled", "disabled");
    $("#qu").css({
        display: "none"
    });
    $.ajax({
        url: root.member.viewMember,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "memberId":memberid
        }),
        success: function (data) {
            console.log(data);
            if(data.member.groundName!=""&& data.member.groundName!=null){
                $("#compaNames").css({
                    display: "block"
                });
            }
            $("#email2").val(data.member.email);
            if(data.member.company_name!=""){
                company_namess=data.member.company_name
                $("#companyNames").val(data.member.company_name);
                $("#companyNames").text(data.member.pushman_company_id);
            }else {
                $("#companyNames").val('');
            }
             if(data.member.customer_leader!=""){
                 $('#customerleaders').val(data.member.customer_leader);
             }else {
                 $('#customerleaders').val("");
             }
                if (data.member.bind_status==20) {
                    $("#xiu").css({
                        display: "none"
                    });
                }else {
                    $("#xiu").css({
                        display: "inline"
                    });
                }
            if(data.member.price_type==10){
                $("#price_types2").prop("checked",true)
            }else  if(data.member.price_type==20){
                $("#price_types1").prop("checked",true)
            }else {
                $("#price_types1").prop("checked",false)
                $("#price_types2").prop("checked",false)
            }


        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}

/*保存收货地址*/
var addmobile = "";
var addlink = "";
var cc = 0;
function savecommom_edit() {
    if($("#companyNames").text()==""){
        $.Huimodalalert('请选择会员归属',2000);
        return false;
    }
   /* if($("#checkPerson3").html().indexOf("输入格式错误") != -1){
        return false;
    }*/
    $.ajax({
        /*root.member.updateMember*/
        url:root.member.updateMember,
        cache: false, //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "companyName":$("#companyNames").val(),
            "companyId":$("#companyNames").text(),
            "memberId":memberid,
            "email":$("#email2").val(),
            "customer_leader":$("#customerleaders").val(),
            optUserId:JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
            optUserName:JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
            "priceType":$("input[name='price_types']:checked").val()
        }),
        success: function (data) {
            $("#dizhi").modal("hide");
            console.log(data);
            if(data.errorCode==302){
                $.Huimodalalert(data.errorMessage,2000);
            }else if(data.errorCode==303) {
                $.Huimodalalert(data.errorMessage,2000);
            }
            init()
            adminzuo();
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });

}

//时间转换
/*function add0(m){return m<10?'0'+m:m }
function formatDate(needTime)
{
    //needTime是整数，否则要parseInt转换
    var time = new Date(needTime);
    var y = time.getFullYear();
    var m = time.getMonth()+1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
}*/
//所属分公司
function gongsi(){
    var user_data = {
        "pageNum":1,
        "pageSize":500,
        "groupName":$("#companyNames").val()

    }
    var succCallBack = function (data, status, response) {
        $("#companyNames").text("")
        if(data.errorCode=="0"){
            var jsonObj =data.group;
            if(jsonObj==""){
                $("#tuank").html("<li>无数据</li> ");
            }else {
                var optionstring = "";
                for (var  i= 0; i < jsonObj.length; i++) {
                    optionstring += "<li  onclick='relation("+ jsonObj[i].id+",\""+jsonObj[i].organization_name+"\")' data-align=\"" + jsonObj[i].id + "\" > " + jsonObj[i].organization_name + "</li>";
                }
                $("#tuank").html(optionstring);
                $("#tuank").show()

            }
        }else{
            $("#tuank").html("<li>无数据</li> ");
        }
    }
    /*root.member.getGroup*/
    web.doAjax(root.member.getGroup,'post',user_data, succCallBack);

}
/*//取光标
$("#companyNames").focus(function () {

});*/
$(document).bind("click",function(e){
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest("#tuank").length == 0 && $(e.target).closest("#companyNames").length == 0){
        //点击id为menu之外且id不是不是open，则触发
        $("#tuank").hide()
    }
})
function relation(id,ce) {
    console.log("11122222223333333444444")
    $("#companyNames").val(ce).text(id)
    $("#tuank").hide()
}
function guanbi() {
    $("#tuank").hide()
}
function xiu(el) {
    if(el==1){
        $("#companyNames").removeAttr("disabled");
        $("#qu").css({
            display: "inline"
        });
        $("#xiu").css({
            display: "none"
        });
    }else if(el==2){
        $("#companyNames").val(company_namess);
        $("#companyNames").attr("disabled", "disabled");
        $("#qu").css({
            display: "none"
        });
        $("#xiu").css({
            display: "inline"
        });
        $("#tuank").hide()
    }

}

//编辑普票信息
function generalvote() {
    $("#generalvote").modal("show");
    $.ajax({
        url: root.member.viewMember,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "memberId":memberid
        }),
        success: function (data) {
            $("#unitname").val(data.generalInvoiceInfo.company_name);
            $("#identificationnumber").val(data.generalInvoiceInfo.taxpayer_code);

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}
//普票信息确认
function Determine() {
    if($("#unitname").val()==''){
        $.Huimodalalert('单位名称不可为空！',2000);
        return false;
    }
    if($("#identificationnumber").val()==''){
        $.Huimodalalert('纳税人识别号不可为空！',2000);
        return false;
    }
    $.ajax({
        url: 'https://'+ window.location.host +'/api/admin/amembership/invoice/updateInvoiceInfoByOrdinary',
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "memberId":memberid,
            "companyName":$("#unitname").val(),
            "taxpayerCode":$("#identificationnumber").val(),
            "invoiceType":10,
            "optUserId":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
            "optUserName":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
        }),
        success: function (data) {
                if(data.errorCode==0){
                    $.Huimodalalert('编辑成功',2000);
                    $("#generalvote").modal("hide");
                    init()
                    adminzuo();
                }else {
                    $.Huimodalalert(data.msg,2000);
                }
        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });


}
//普票信息取消
function close_generalvote() {
    $("#generalvote").modal("hide");
    $("#unitname").val("")
    $("#identificationnumber").val("")
}
//普票信息X
function guanbi2() {
    $("#generalvote").modal("hide");
    $("#unitname").val("")
    $("#identificationnumber").val("")
}
